<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑文章</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f4f4f9;
            margin: 0;
            padding: 20px;
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }

        .container {
            display: flex;
            gap: 30px;
            max-width: 1200px;
            margin: 0 auto;
        }

        .left-column {
            flex: 0 0 40%;
            /* 限制左侧列宽度为容器宽度的 40% */
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            padding: 30px;

        }

        .right-column {
            flex: 1;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            padding: 30px;
        }

        /* 原始文章信息样式 */
        #original-article h2 {
            color: #555;
            font-size: 1.5em;
            margin-bottom: 20px;
        }

        #original-article p {
            color: #777;
            line-height: 1.6;
            margin-bottom: 15px;
        }

        /* 表单样式 */
        #edit-form label {
            display: block;
            font-weight: 600;
            color: #555;
            margin-bottom: 8px;
        }

        #edit-form input[type="text"],
        #edit-form textarea {
            width: 100%;
            padding: 12px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
            transition: border-color 0.3s ease;
        }

        #edit-form input[type="text"]:focus,
        #edit-form textarea:focus {
            border-color: #007BFF;
            outline: none;
        }

        /* 按钮样式 */
        #edit-form input[type="submit"] {
            background-color: #007BFF;
            color: #fff;
            padding: 12px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        #edit-form input[type="submit"]:hover {
            background-color: #0056b3;
        }

        .origincontent {
            max-width: 100%;
            max-height: 50vh;
            word-wrap: break-word;
            /* 允许长单词或无法使用断点的 URL 自动换行 */
            word-break: break-all;
            /* 强制换行，即使单词很长 */
            overflow-y: auto;
            /* 垂直方向允许滚动 */
        }

        .original-image {
            max-width: 100%;
            max-height: 20vh;
        }

        .button-container {
            display: flex;
            width: 100%;
            justify-content: space-between;
        }

        .back {
            width: 100px;
            background-color: #4CAF50;
            color: #fff;
            border-radius: 4px;
        }

        /* 加载圈圈样式 */
        #loading {
            display: none;
            border: 16px solid #f3f3f3;
            border-top: 16px solid #3498db;
            border-radius: 50%;
            width: 120px;
            height: 120px;
            animation: spin 2s linear infinite;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1000;
        }

        @keyframes spin {
            0% {
                transform: translate(-50%, -50%) rotate(0deg);
            }

            100% {
                transform: translate(-50%, -50%) rotate(360deg);
            }
        }
        /*给文本编辑框加长*/
        #editor-container {
            height: 400px;
            margin: 10px 0;
            border: 1px solid #ccc;
        }
    </style>
</head>

<body>
<h1>编辑文章</h1>
<div class="container">
    <!-- 左侧显示原始文章信息 -->
    <div class="left-column" id="original-article">
        <!-- 文章信息将通过 JavaScript 动态插入 -->
    </div>
    <!-- 右侧显示修改表单 -->
    <div class="right-column">
        <form id="edit-form">
            <label for="title">标题:</label>
            <input type="text" id="title" name="title"><br>

            <label for="category">分类:</label>
            <input type="text" id="category" name="category"><br>
            <label for="source">来源:</label>
            <input type="text" id="source" name="source"><br>
            <label for="date">日期:</label>
            <input type="text" id="date" name="date"><br>
            <label for="location">地点:</label>
            <input type="text" id="location" name="location"><br>
            <label for="signMethod">报名方式:</label>
            <input type="text" id="signMethod" name="signMethod"><br>
            <label for="rule">参加规则:</label>
            <input type="text" id="rule" name="rule"><br>
            <label for="image">图片:</label>
            <input type="file" id="image" name="image" accept="image/*"><br><br>

            <!-- 替换 textarea 为编辑器容器 -->
            <label for="editor-content">文章内容:</label>
            <div id="toolbar-container"></div>
            <div id="editor-container"></div>
            <input type="hidden" id="editor-content" name="content">

            <div class="button-container">
                <input type="submit" value="保存修改">
                <button type="button" onclick=" window.location.href = '/admin/home'" class="back">返回</button>
            </div>
        </form>

    </div>
</div>
<!-- 加载圈圈元素 -->
<div id="loading"></div>
<script src="/dist/wangEditor.js"></script>
<script>
    // 创建编辑器实例
    const E = window.wangEditor;
    const editor = new E('#toolbar-container', '#editor-container');
    // 配置编辑器
    // 配置图片上传服务器地址
    editor.config.uploadImgServer = '/richtext/image/upload';
    // 配置表单中文件字段名
    editor.config.uploadFileName = 'image';
    // 启用编辑器内置压缩（自动处理大文件）
    editor.config.uploadImgShowBase64 = true; // 可选：小图转 Base64
    editor.config.uploadImgMaxSize = 5 * 1024 * 1024; // 限制为 5MB
    editor.config.uploadImgCompress = true; // 开启压缩
    // 配置最多可上传的文件数量
    editor.config.uploadImgMaxLength = 1;
    // 配置允许上传的文件类型
    editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp'] // 确保包含 png
    // 创建并初始化编辑器
    editor.create();
    // 同步内容到隐藏域,设置 onchange 配置项
    editor.config.onchange = function (newHtml) {
        const contentInput = document.getElementById('editor-content');
        contentInput.value = newHtml;
    };

    // 加载文章数据
    let article = {};
    // 获取当前 URL 的查询参数
    const urlParams = new URLSearchParams(window.location.search);
    // 提取文章 ID
    const articleId = parseInt(urlParams.get('id'));
    const url = `/article/${articleId}`;
    const titleInput = document.getElementById('title');
    const contentInput = document.getElementById('editor-content');
    const categoryInput = document.getElementById('category');
    const sourceInput = document.getElementById('source');
    const dateInput = document.getElementById('date');
    const signMethodInput = document.getElementById('signMethod');
    const ruleInput = document.getElementById('rule');
    const locationInput = document.getElementById('location');
    // 加载文章数据
    const save = () => {
        article.theme = titleInput.value;
        article.content = contentInput.value;
        article.type = categoryInput.value;
        article.origin = sourceInput.value;
        article.date = dateInput.value;
        article.signMethod = signMethodInput.value;
        article.rule = ruleInput.value;
        article.location = locationInput.value;
        const newImage = document.getElementById('image').files[0];
        if (newImage) {
            const objectURL = URL.createObjectURL(newImage);
            article.image = objectURL;
            // 当不再需要这个 URL 时，释放它以节省内存
            const img = new Image();
            img.onload = function () {
                URL.revokeObjectURL(objectURL);
            };
            img.src = objectURL;
        }
        console.log("article", article);
    }
    // 加载文章数据
    const render = () => {
        const originalArticleDiv = document.getElementById('original-article');
        originalArticleDiv.innerHTML = `
                    <h2>原始文章信息</h2>
                    <p><strong>标题:</strong> ${article.theme}</p>
                    <p><strong>分类:</strong> ${article.type}</p>
                    <p><strong>来源:</strong> ${article.origin}</p>
                    <p><strong>日期:</strong> ${article.date}</p>
                    <p><strong>地点:</strong> ${article.location}</p>
                    <p><strong>报名方式:</strong> ${article.signMethod}</p>
                    <p><strong>参加规则:</strong> ${article.rule}</p>
                    <img src="${article.image}" alt="原始图片" class="original-image"><br>

                    <div class = "origincontent"><strong>内容:</strong> ${article.content}</div>
                `;
        // 填充修改表单
        titleInput.value = article.theme;
        // 将内容设置到编辑器容器中
        editor.txt.html(article.content);
        // 同步到隐藏域（可选，根据编辑器配置决定是否需要）
        contentInput.value = article.content;

        categoryInput.value = article.type;
        sourceInput.value = article.origin;
        dateInput.value = article.date;
        signMethodInput.value = article.signMethod;
        ruleInput.value = article.rule;
        locationInput.value = article.location;
        // 处理表单提交事件
        const editForm = document.getElementById('edit-form');
        editForm.addEventListener('submit', async function (event) {
            event.preventDefault();
            // 显示加载圈圈
            const loading = document.getElementById('loading');
            loading.style.display = 'block';
            // 禁用提交按钮，防止重复提交
            const submitButton = this.querySelector('input[type="submit"]');
            submitButton.disabled = true;
            // 收集表单数据
            const formData = new FormData();
            formData.append('article.type', categoryInput.value);
            formData.append('article.theme', titleInput.value);
            formData.append('article.origin', sourceInput.value);
            formData.append('article.date', dateInput.value);
            formData.append('article.signMethod', signMethodInput.value);
            formData.append('article.rule', ruleInput.value);
            formData.append('article.location', locationInput.value);
            formData.append('article.content', contentInput.value);
            const imageFile = document.getElementById('image').files[0];
            if (imageFile) {
                formData.append('image', imageFile);
                console.log('用户选择了新图片，已添加到表单数据中');
            } else {
                formData.append('image', article.image || '');
                alert('未选择新图片');
                // 隐藏加载圈圈
                loading.style.display = 'none';
                // 启用提交按钮
                submitButton.disabled = false;
                return;
            }
            fetch(url, {
                method: 'PUT',
                body: formData,
                credentials: 'include' // 确保发送请求时带上Cookie
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 0) {
                        save()
                        render();
                        alert('修改成功！');
                        // window.location.href = 'dashboard.html';
                    } else {
                        alert('修改失败！');
                        console.error('修改失败：', data.message);
                    }
                })
                .catch(error => {
                    console.error('请求出错：', error);
                    alert('请求出错，请稍后重试');
                })
                .finally(() => {
                    // 隐藏加载圈圈
                    loading.style.display = 'none';
                    // 启用提交按钮
                    submitButton.disabled = false;
                });
        });
    }
    if (articleId) {
        console.log('获取到的文章 ID:', articleId);
        fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 0) {
                    console.log('查询成功，文章属性：', data.data);
                    article = data.data;
                    render();
                } else {
                    console.error('查询失败：', data.message);
                }
            })
            .catch(error => {
                console.error('error:', error);
            });

    }
</script>
</body>

</html>